package jwanalytics.dbloader;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/** 
 * For retrieval of properties stored in jwanalytics.properties file. 
 * This is the configuration mechanism for jwanalytics add-on.
 * The configuration file is located at the src/ directory.
 */
public class Props {
	
	/** Properties file used by this package. */
	public static final String PROPS_FILE = "jwanalytics.properties"; 
	
    /** Properties loaded from file in the classpath named jwa.properties */
	public static Map<String, Properties> fileAndProperties = new HashMap<String, Properties>();
    
	/**
	 * @param propertiesFile Typically jwanalytics.properties.
	 */
	public static void init(String propertiesFile, boolean forceReload) {
    	if (fileAndProperties.containsKey(propertiesFile) && !forceReload) {
    		return; //@TODO: later we should create a force reload method.
    	}
    	
       	try {
       	  Properties props = new java.util.Properties();       		
       	  java.net.URL url = ClassLoader.getSystemResource(propertiesFile);
  		  if (url == null) { //could cause a null pointer exception not picked-up on the catch below.
  			  throw new IllegalStateException("Could not load properties file:"+propertiesFile);
  		  }
  		  props.load(url.openStream());
  		  fileAndProperties.put(propertiesFile, props);
		} catch (IOException e) {
			throw new IllegalStateException("Could not load properties file:"+propertiesFile);
		}    	
    }
    
    /** Obtains a property from the .properties file. */
    public static String get(String file, String key) {
    	return (String) fileAndProperties.get(file).getProperty(key);
    }
	
}
